package Network;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UDPEchoClient {
    private DatagramSocket socket = null;
    private String serverIp;
    private int serverPort;
    public  UDPEchoClient(String serverIp , int serverPort) throws SocketException {
        socket = new DatagramSocket();
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }
    public void start() throws IOException {
        System.out.println("客户端启动！！！");
        Scanner scanner = new Scanner(System.in);
        while(true) {
            //1.从控制台读取用户输入
            System.out.print("请输入要发送的请求 ：");
            String request  = scanner.next();
            //2.构造请求并发送给服务器
            //构造请求数据的时候，不仅要有数据，还要有目标
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),0,request.getBytes().length
             , InetAddress.getByName(serverIp),serverPort);
            socket.send(requestPacket);

            //3.读取响应数据
            DatagramPacket responsePacker =  new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacker);
            //4.将响应输出在控制台
            String response = new String(responsePacker.getData(),0,responsePacker.getLength());
            System.out.println(response);
        }

    }

    public static void main(String[] args) throws IOException {
        UDPEchoClient client = new UDPEchoClient("127.0.0.1",9090);
        client.start();

    }
}
